/*
一个使用线程的简单定时器实现
*/

#ifndef __timer_H__
#define __timer_H__

#include <thread>
#include <chrono>
#include <atomic>
#include <functional>

class Timer
{
public:
    Timer(int32_t repeat = 1);
    ~Timer();

    //启动定时任务
    //millisecond 定时器间隔时间
    //func 回调函数
    //args 回调函数参数
    template<typename F, typename... Arg>
    void Start(uint64_t millisecond, F&& func, Arg&&... args);

    //关闭定时任务
    void stop();

private:
    std::thread       m_thread;     
    std::atomic<bool> m_active;     //判断当前线程是否在执行
    std::function<void()> m_func;
    uint64_t m_period;  //定时器间隔时间,毫秒
    int32_t  m_repeat;  //定时器触发次数,-1为无限触发
};


//启动定时任务
template<typename F, typename... Arg>
void Timer::Start(uint64_t millisecond, F&& func, Arg&&... args)
{
    if(this->m_active.load())
    {
        return;
    }

    m_period = millisecond;
    m_func = std::bind(std::forward<F>(func), std::forward<Arg>(args)...);

    m_active.store(true);

    m_thread = std::thread([this](){
        if(m_repeat < 0)
        {
            while(m_active)
            {
                //让当前线程睡眠
                std::this_thread::sleep_for(std::chrono::milliseconds(m_period));
                if(!m_active) //如果线程被取消
                {
                    return;
                }
                m_func();
            }
        }
        else
        {
            while(m_repeat > 0)
            {
                std::this_thread::sleep_for(std::chrono::milliseconds(m_period));
                if(!m_active) //如果线程被取消
                {
                    return;
                }
                m_func();
                --m_repeat;
            }
        }
    });
    m_thread.detach();
}




#endif
